/******************************************************************************
 *
 * Project:		mGameEngine
 * File:		motionblur.cpp
 * Author:		karooolek
 * Created on:	2009-09-10
 *
 ******************************************************************************/

#include "motionblur.h"

namespace mGameEngine
{
namespace Graphics
{

MotionBlur::MotionBlur(float delay,
		const Texture *texture, RenderTarget *target) :
	PostProcess(NULL, texture, target),
	_last(), _timer(), _delay(delay)
{
	static const String &vertSrc
	(
#include "postprocess.vert"
	);
	static const String &fragSrc
	(
#include "mix.frag"
	);
	_gpuProgram = new GPUProgram(vertSrc, fragSrc);
	_gpuProgram->compile();
}

MotionBlur::~MotionBlur()
{
}

void MotionBlur::setDelay(float delay)
{
	if(delay < 0.0f)
	{
		return;
	}

	_delay = delay;
}

void MotionBlur::process() const
{
	// motion-blur disabled
	if(!_gpuProgram || !_enabled)
	{
		return PostProcess::process();
	}

	// calculate decay every frame
	if(_gpuProgram)
	{
		float dt = _timer.getTime();
		_timer.reset();
		float decay = pow(0.5f, 4.0f/_delay * dt);
		_gpuProgram->setValue("a", decay);
	}

	// set last frame texture
	_gpuProgram->setTexture("texture2", &_last, 1);

	// render to output target
	PostProcess::process();

	// render to last texture
	_last.setSize(_output->getSize());
	RenderTarget *tmp = _output;
	_output = &_last;
	PostProcess::process();
	_output = tmp;
}

}
}

